package com.example.rtmppush;

import android.media.projection.MediaProjection;
import android.util.Log;

import java.util.concurrent.LinkedBlockingDeque;

// 录屏直播 线程
public class ScreenLive extends Thread{

    private String TAG ="ScreenLive";
    private String liveUrl;
    MediaProjection mediaProjection;
    private boolean isLive;
    private String savePath;

    // 阻塞队列
    private LinkedBlockingDeque<RTMPPacket> queue = new LinkedBlockingDeque<>();

    static {
        System.loadLibrary("rtmppush");
    }


    public void  addPacket(RTMPPacket dataPacket) {
        if (isLive  && queue.size()<100) {
            queue.add(dataPacket);
        }else {
            Log.e(TAG,"队列太大 展示不编码");
        }
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public void startLive(String liveUrl, MediaProjection mediaProjection) {
        this.liveUrl = liveUrl;
        this.mediaProjection = mediaProjection;

    }
    private native boolean connect(String liveUrl);

    private native boolean sendData(byte[] data, int len, long tms,int type);

    @Override
    public void run() {
        super.run();
        isLive = true; // 开始直播
        // TODO 调用native 链接RTMP
        if (!connect(liveUrl)) {
            Log.e("rtmp","链接失败......");
            return;
        }
        VideoCodec videoCodec = new VideoCodec(mediaProjection,this);
        videoCodec.setPath(savePath);
        videoCodec.start();
        while (isLive) {
            RTMPPacket rtmpPacket = null;
            try {
                Log.e(TAG,"剩余大小-----："+queue.size());
                rtmpPacket = queue.take();
                Log.e(TAG,"剩余大小："+queue.size());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            if (rtmpPacket!=null && rtmpPacket.getBuffer()!=null
                    && rtmpPacket.getLength()!=0) {
                Log.e(TAG,"推送数据成功");
                sendData(rtmpPacket.getBuffer(),rtmpPacket.getLength(),rtmpPacket.getTms(),rtmpPacket.getType());
            }else {
                Log.e(TAG,"推送数据失败");
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();

    }
}
